package com.yh.autobio.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.yh.autobio.AppConfig;
import com.yh.autobio.AppContext;
import com.yh.autobio.R;
import com.yh.autobio.api.RetrofitSingleton;
import com.yh.autobio.base.BaseFragment;
import com.yh.autobio.common.PLog;
import com.yh.autobio.common.StringUtils;
import com.yh.autobio.common.UIHelper;
import com.yh.autobio.component.dialog.DialogHelp;
import com.yh.autobio.gddb.gbmanager.MatCountManager;
import com.yh.autobio.gddb.gbmanager.MatManager;
import com.yh.autobio.gddb.gdbean.MatBean;
import com.yh.autobio.gddb.gdbean.MatBeanCount;
import com.yh.autobio.modules.adatper.Sale_AddAdapter;
import com.yh.autobio.modules.bean.CustPhone;
import com.yh.autobio.modules.bean.KCQty;
import com.yh.autobio.modules.bean.SimpleBackPage;
import com.yh.autobio.modules.ui.empty.EmptyLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yh.autobio.AppConfig.SCN_CUST_ACTION_SCODE;

/**
 * =========================
 * 版权所有，违法必究
 * 作者：john
 * <p>
 * 工程：FoodBarcode
 * <p>
 * 文件名：ComListFragment
 * <p>
 * 创建时间：2017.05.25.15:49
 * *****************************
 */
public class GiftListFragment extends BaseFragment implements Sale_AddAdapter.OnSaleAddAdapterListern {
//    @InjectView(R.id.recycleview)
//    RecyclerView mRecycleview;

    @InjectView(R.id.id_stickynavlayout_innerscrollvie)
    RecyclerView mRecycleview;
    @InjectView(R.id.error_layout)
    EmptyLayout errorLayout;

    public Sale_AddAdapter mAdapter;
    ArrayList<MatBeanCount> checkedCKS;
    private String mUserName;
    public String FDCStockName;
    public String FDCStockId;
//    @InjectView(R.id.scrollView)
//    ScrollView scrollView;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE) && isCurr) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                handleOtherText(message);
            } else if (intent.getAction().equals(AppConfig.UPDATA_BODY)) {
                initData();
            }
        }
    };
    private ItemTouchHelper mItemTouchHelper;
    private String mType;


    @Override
    public void onCountChanger(String id, String count) {
//        MatCountManager.getInstance(mActivity).updateCount(id,"1",count + "");
    }

    @Override
    public void onMoneyChanged() {

    }

    public static boolean isCurr = false;

    private void handleOtherText(final String text) {

        if (dialog != null) {
            if (dialog.isShowing())
                dialog.dismiss();
        }
        //先去判断扫描的单号是否存在
        boolean matExist = MatManager.getInstance(mActivity).isMatExist(text, "0");
        if (matExist) {//存在
            //再去判断扫描的单号对应几个物料
            boolean mulMat1 = MatManager.getInstance(mActivity).isMulMat(text, "0");
            if (mulMat1) {//为true说明对应多个物料
                choiceSingleMat(text);
            } else {//走else说明只对应一个物料
                onlyMatInsert(text);
            }
        } else {//不存在
            Snackbar.make(mActivity.getWindow().getDecorView(), "出库单不匹配，请重新扫描或同步数据！", Snackbar.LENGTH_SHORT).show();
        }
    }


    //扫描条码只对应一个物料时的添加流程
    private void onlyMatInsert(String barcode) {
        //先判断已添加的中是否存在
        List<MatBeanCount> listMatBean = mAdapter.getListMatBean();
        for (int i = 0; i < listMatBean.size(); i++) {
            String id = listMatBean.get(i).getBarcode();
            if (barcode.equals(id)) {
                int count = Integer.parseInt(listMatBean.get(i).getCount()) + 1;
                listMatBean.get(i).setCount(count + "");
//                MatCountManager.getInstance(mActivity).updateCount(barcode, "1", count + "");
//                mRecycleview.setAdapter(mAdapter);
                mRecycleview.scrollToPosition(i);
                mAdapter.notifyItemChanged(i);
                return;
            }
        }

//        int matCount = MatCountManager.getInstance(mActivity).getMatCountByType("1");
        MatBean matById = MatManager.getInstance(mActivity).getMatById(barcode, "1");
        MatBeanCount matBean = new MatBeanCount();
        matBean.setId(matById.getId());
        matBean.setName(matById.getName());
        matBean.setNumber(matById.getNumber());
        matBean.setUnitgroup_name(matById.getUnitgroup_name());
        matBean.setUnitgroup_id(matById.getUnitgroup_id());
        matBean.setUnit_name(matById.getUnit_name());
        matBean.setUnit_id(matById.getUnit_id());
        matBean.setCount("1");
        matBean.setModel(matById.getModel());
        matBean.setType("1");
        matBean.setBarcode(matById.getBarcode());
        matBean.setCredit(matById.getCredit());
        matBean.setUserName(mUserName);
        matBean.setFDCStockID(FDCStockId);
        matBean.setFDCStockName(FDCStockName);
//        matBean.setPosotion(matCount + "");
        matBean.setSaleprice(Double.parseDouble(matById.getSaleprice()));


        if (!StringUtils.isEmpty(FDCStockId)) {
            this.headCKName = FDCStockName;
            this.bean = matBean;
            showWaitDialog();
            RetrofitSingleton.getApiService(mActivity).
                    GetFirstStock(FDCStockId, matById.getId())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        } else {
            checkedCKS.add(matBean);
            mAdapter = new Sale_AddAdapter(mActivity, checkedCKS, this, "1",mType);
            mRecycleview.setAdapter(mAdapter);
            if (checkedCKS.size() > 1)
                mRecycleview.scrollToPosition(checkedCKS.size() - 1);
        }

//        MatCountManager.getInstance(mActivity).insertMat(matBean);//缓存
//        mHandler.post(new Runnable() {
//            @Override
//            public void run() {
//                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//            }
//        });

    }

    private AlertDialog dialog;

    //从多个物料中选择一个加入缓存并刷新页面
    private void choiceSingleMat(String barcode) {

        //拿到该条码对应多个物料
        final ArrayList<MatBean> mulMat = MatManager.getInstance(mActivity).getMulMat(barcode, "1");
        String[] strings = new String[mulMat.size()];
        for (int i = 0; i < mulMat.size(); i++) {
            strings[i] = mulMat.get(i).getName();
        }
        dialog = DialogHelp.getSingleChoiceDialog(mActivity, "种类", strings, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String id = mulMat.get(i).getId();
                //先判断已添加的中是否存在
                List<MatBeanCount> listMatBean = mAdapter.getListMatBean();
                for (int j = 0; j < listMatBean.size(); j++) {
                    MatBeanCount matBeanCount = listMatBean.get(j);
                    String ids = matBeanCount.getId();
                    if (id.equals(ids)) {//已添加过同类型物料
                        int count = Integer.parseInt(listMatBean.get(j).getCount()) + 1;
                        matBeanCount.setCount(count + "");
//                        MatCountManager.getInstance(mActivity).updateMat(matBeanCount);
//                        mRecycleview.setAdapter(mAdapter);
                        dialogInterface.dismiss();
                        mRecycleview.scrollToPosition(j);
                        mAdapter.notifyItemChanged(j);
                        return;
                    }
                }

//                int matCount = MatCountManager.getInstance(mActivity).getMatCountByType("1");
                MatBean matById = MatManager.getInstance(mActivity).getMatById(id);
                MatBeanCount matBean = new MatBeanCount();
                matBean.setId(matById.getId());
                matBean.setName(matById.getName());
                matBean.setNumber(matById.getNumber());
                matBean.setUnitgroup_name(matById.getUnitgroup_name());
                matBean.setUnitgroup_id(matById.getUnitgroup_id());
                matBean.setUnit_name(matById.getUnit_name());
                matBean.setUnit_id(matById.getUnit_id());
                matBean.setCount("1");
                matBean.setModel(matById.getModel());
                matBean.setType("1");
                matBean.setBarcode(matById.getBarcode());
                matBean.setUserName(mUserName);
                matBean.setFDCStockID(FDCStockId);
                matBean.setFDCStockName(FDCStockName);
                matBean.setCredit(matById.getCredit());
//                matBean.setPosotion(matCount + "");
                matBean.setSaleprice(Double.parseDouble(matById.getSaleprice()));


                if (!StringUtils.isEmpty(FDCStockName)) {
                    dialogInterface.dismiss();
                    GiftListFragment.this.headCKName = FDCStockName;
                    GiftListFragment.this.bean = matBean;
                    showWaitDialog();
                    RetrofitSingleton.getApiService(mActivity).
                            GetFirstStock(FDCStockId, matById.getId())
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(observer);

                } else {
                    checkedCKS.add(matBean);
                    mAdapter = new Sale_AddAdapter(mActivity, checkedCKS, GiftListFragment.this, "1",mType);
                    mRecycleview.setAdapter(mAdapter);
                    dialogInterface.dismiss();
                    if (checkedCKS.size() > 1)
                        mRecycleview.scrollToPosition(checkedCKS.size() - 1);
                }


//                MatCountManager.getInstance(mActivity).insertMat(matBean);//缓存
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//                    }
//                });
            }
        }).show();
    }

    @Override
    public String getTitle() {
        return "赠 品";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_matorgift, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        isCurr = false;
        Bundle bundle = getArguments();
        mType = bundle.getString("TYPE");
        mUserName = AppContext.getInstance().getCurrentUser().getName();
        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        intentFilter.addAction(AppConfig.UPDATA_BODY);
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);
//        BaseViewPagerFragment.setonPageChangeListener(new BaseViewPagerFragment.OnPageChangeListener() {
//            @Override
//            public void onPageSelected(int position) {
//                try {
//                    if (1 == position) {
//                        GiftListFragment.this.isCurr = true;
//                        ComListFragment.isCurr = false;
//                    } else if (0 == position) {
//                        GiftListFragment.this.isCurr = false;
//                        ComListFragment.isCurr = true;
//                    }
//
//                } catch (Exception ex) {
//                }
//            }
//        });


        ADDSaleOutFragment.setonPageChangeListener(new ADDSaleOutFragment.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                try {
                    if (1 == position) {
                        GiftListFragment.this.isCurr = true;
                        ComListFragment.isCurr = false;
//                        PLog.d("zh",position+"======1=");
                    } else if (0 == position) {
                        GiftListFragment.this.isCurr = false;
                        ComListFragment.isCurr = true;
//                        PLog.d("zh",position+"======0=");
                    }

                } catch (Exception ex) {
                }
            }
        });


        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecycleview.setLayoutManager(layoutManager);
        checkedCKS = new ArrayList<>();
        mAdapter = new Sale_AddAdapter(mActivity, checkedCKS, this, "1",mType);
        //关联ItemTouchHelper和RecyclerView
//        ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(mAdapter);
//        mItemTouchHelper = new ItemTouchHelper(callback);
//        mItemTouchHelper.attachToRecyclerView(mRecycleview);
    }

    @Override
    public void initData() {
        super.initData();

        Bundle bundle = getArguments();
        String headId = bundle.getString("HEADID");

        if ("show".equals(mType)) {
            ArrayList<MatBeanCount> allMats = MatCountManager.getInstance(mActivity).getAllMatsByType("1", headId);
            checkedCKS.addAll(allMats);
        } else {

        }
        mRecycleview.setAdapter(mAdapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            mActivity.unregisterReceiver(mSamDataReceiver);
        } catch (Exception ex) {
        }
        ButterKnife.reset(this);
    }


    private int position;

    public void setGoTop() {
        mRecycleview.smoothScrollToPosition(0);
    }


    private CustPhone item;
    private MatBeanCount bean;
    private String headCKName;

    //adapter中点击了选择发货仓库
    @Override
    public void onFHCKClick(final MatBeanCount bean, final int position) {
        this.position = position;
        Bundle bundle = new Bundle();
        bundle.putString("type", "fhck");
        bundle.putString("mold", "gift");
        CustPhoneListFragment.setOnItemClickListener(new CustPhoneListFragment.OnItemClickListener() {
            @Override
            public void onComClick(CustPhone item) {
            }

            @Override
            public void onGiftClick(CustPhone item) {
//                MatHeadBean HeadBean = new MatHeadBean();
//                HeadBean.setId(item.getId());
//                HeadBean.setValue(item.getName());
//                HeadBean.setName("CUS发货仓库");
//                HeadBean.setPosition(position + "");
//                HeadBean.setFtype("1");
//                MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);
//                MatCountManager.getInstance(mActivity).updateFHCKByPos("1",position+"",item);

                bean.setTDCStockID(item.getId());
                bean.setTDCStockName(item.getName());

                GiftListFragment.this.bean = bean;
                GiftListFragment.this.item = item;

                showWaitDialog();
                RetrofitSingleton.getApiService(mActivity).
                        GetFirstStock(item.getId(), bean.getId())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(observer);


//                mAdapter.notifyItemChanged(position);
            }
        });
        UIHelper.showSimpleBackForResult(GiftListFragment.this, mActivity, 7, SimpleBackPage.CUST_PHEON, bundle, "发货仓库");
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (data != null) {
//            final CustPhone item = (CustPhone) data.getSerializableExtra("item");
//            if (item != null) {
//                MatHeadBean HeadBean = new MatHeadBean();
//                HeadBean.setId(item.getId());
//                HeadBean.setValue(item.getName());
//                switch (requestCode) {
//                    case 7://adapter中点击发货仓库 自选的仓库
//                        HeadBean.setName("CUS发货仓库");
//                        HeadBean.setPosition(position + "");
//                        MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);
//                        mAdapter.notifyItemChanged(position);
//                        break;
//                }
//            }
//        }
//    }


    Observer<KCQty> observer = new Observer<KCQty>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            Snackbar.make(getActivity().getWindow().getDecorView(), e.getMessage(), Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(KCQty kc) {
            hideWaitDialog();
            if (!StringUtils.isEmpty(headCKName)) {
                bean.setQty(kc.getQty());
                checkedCKS.add(bean);
                mAdapter = new Sale_AddAdapter(mActivity, checkedCKS, GiftListFragment.this, "0",mType);
                mRecycleview.setAdapter(mAdapter);
                if (checkedCKS.size() > 1)
                    mRecycleview.scrollToPosition(checkedCKS.size() - 1);
                headCKName = null;
            } else {
//                bean.setTDCStockID(bean.getId());
//                bean.setTDCStockName(item.getName());
                bean.setQty(kc.getQty());
                mAdapter.notifyItemChanged(position);
            }


        }
    };


}
